package com.ctrip.ec.api.admin.filter;
import com.ctrip.ec.api.admin.common.*;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by jiangzy on 2018/5/2.
 */
public class AuthFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }


    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request =  (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String token =  request.getHeader("auth-token");


        // 指定允许其他域名访问

        response.setHeader("Access-Control-Allow-Origin", "*");

// 响应类型

        response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE");

// 响应头设置

        response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, auth-token");

        if ("OPTIONS".equals(request.getMethod())){

            response.setStatus(response.SC_NO_CONTENT);
            //  response.setHeader(" Access-Control-Max-Age","3600");

        }

        boolean hasLogin = false;
        if(token!= null && token.length()>0){
            try {
                RequestContext.setLoginToken(token);
                hasLogin = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(hasLogin == false && !(request.getRequestURI().contains("user/login") || request.getRequestURI().contains("tool/table") )){
            ResultBody  body= new ResultBody(ResponseStatus.Unauthorized.getId() ,"未登录或登录超时",null);

            ObjectMapper mapper = new ObjectMapper();
            JsonMapper jm = new JsonMapper(mapper);
            servletResponse.setContentType("application/json; charset=UTF-8");
            jm.writeValue(servletResponse.getWriter(), body);
            servletResponse.flushBuffer();

        }else {
            filterChain.doFilter(servletRequest, servletResponse);
            RequestContext.clearLoginToken();
        }


    }

    public void destroy() {

    }
}
